package com.yidu.manage.controller.base;

import com.yidu.common.utils.ResultUtil;
import com.yidu.manage.domain.SysMenu;
import com.yidu.manage.domain.SysRole;
import com.yidu.manage.domain.SysUser;
import com.yidu.manage.domain.model.LoginUser;
import com.yidu.manage.service.ISysRoleService;
import com.yidu.manage.service.ITSysMenuService;
import com.yidu.manage.service.ITSysUserService;
import com.yidu.manage.service.system.CurrentUser;
import com.yidu.manage.utils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class LoginController
{
    @Autowired
    private ITSysUserService sysUserService;

    @Autowired
    private ITSysMenuService sysMenuService;

    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 登录方法
     *
     * @param user 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public Object login(@RequestBody LoginUser user)
    {
        SysUser sysUser = sysUserService.login(user.getUsername(), user.getPassword());
        if (sysUser == null)
        {
            return ResultUtil.error("登陆失败");
        }
        LoginUser u = LoginUser.of(sysUser);
        List<SysRole> roleList = sysRoleService.findSysRoleListById(u.getId());
        List<String> roles = roleList.stream().map(SysRole::getRoleName).collect(Collectors.toList());

        String token = JwtTokenUtils.createToken(u.getUsername(), roles, u.isRememberMe());
        return ResultUtil.success(Map.of("token", token, "user", sysUser));
    }

    @GetMapping("/login")
    public Object loginC()
    {
        return ResultUtil.success("ok");
    }

    @PostMapping("/logout")
    public Object logout()
    {
        return ResultUtil.success("ok");
    }

    @GetMapping("/getInfo")
    @PreAuthorize("@ss.hasPermit('manage:user:getInfo')")
    public Object getInfo()
    {
        SysUser user = sysUserService.getById(CurrentUser.getCurrentUser().getId());
        return ResultUtil.success(user);
    }

    @GetMapping("getRouters")
    public Object getRouters()
    {
        CurrentUser.getCurrentUser();
        LoginUser user = CurrentUser.getCurrentUser();
        if (user == null)
        {
            return ResultUtil.error("user is null!");
        }
        List<SysMenu> menus = sysMenuService.selectMenuTreeByUserId(user.getId());
        return ResultUtil.success(sysMenuService.buildMenus(menus));
    }
}
